package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/teacher/loginProcess")
public class TeacherLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Connectmysql cmysql = new Connectmysql(
                "jdbc:mysql://localhost:3306/exam",
                "root",
                "root",
                "com.mysql.cj.jdbc.Driver");

        ResultSet rst = null;
        try {
            if (cmysql.open()) {
                rst = cmysql.executeSql(
                        "SELECT teacher_id, teacher_no, name, gender, phone, email, title FROM teacher " +
                                "WHERE username = ? AND password = ? AND status = 1",
                        new Object[]{username, password}
                );

                if (rst != null && rst.next()) {
                    HttpSession session = request.getSession();
                    session.setAttribute("teacher_id", rst.getInt("teacher_id"));
                    session.setAttribute("teacher_no", rst.getString("teacher_no"));
                    session.setAttribute("teacher_name", rst.getString("name"));
                    session.setAttribute("gender", rst.getInt("gender") == 1 ? "男" : "女");
                    session.setAttribute("phone", rst.getString("phone"));
                    session.setAttribute("email", rst.getString("email"));
                    session.setAttribute("title", rst.getString("title"));

                    session.setMaxInactiveInterval(30 * 60);
                    response.sendRedirect(request.getContextPath() + "/teacher.jsp");
                } else {
                    request.setAttribute("error", "用户名或密码错误");
                    request.getRequestDispatcher("/teacher_student.jsp").forward(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库错误");
            request.getRequestDispatcher("/teacher_student.jsp").forward(request, response);
        } finally {
            if (rst != null) {
                try {
                    rst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            cmysql.close();
        }
    }
}